﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mshtml;

namespace SevenDragon
{
    public partial class indexbuilder : Form
    {

        System.Uri url;
        DataClasses1DataContext ctx;
        int pageindex;//当前页数
        string URLprefix = @"http://www.jjwxc.net/bookbase_slave.php?submit=&orderstr=3endstr=true&endstr=true&page=";
        string URLsuffix = @"&booktype=";
        string Linkprefix = @"http://www.jjwxc.net/onebook.php?novelid=";

        object obj;
        

        public indexbuilder()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ctx = new DataClasses1DataContext();
            obj = new object();
            this.timer1.Enabled = true;
            //浏览器加载成功

            this.pageindex = 51;

            this.url = new Uri(URLprefix + this.pageindex.ToString()+URLsuffix);
            this.webBrowser1.Url = url;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //if (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            //{
            //    return;
            //}

            //try
            //{
            //    //DOM成功
            //    IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;

            //    GetIndex(vDocument.links);

            //    //test
            //    if (this.pageindex > 1895)
            //    {
            //        Application.Exit();
            //    }
            //    //

            //    this.pageindex += 1;
            //    this.url = new Uri(URLprefix + this.pageindex.ToString() + URLsuffix);
            //    this.webBrowser1.Url = url;
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}

        }


        /// <summary>
        /// 获取index
        /// </summary>
        /// <param name="links"></param>
        private void GetIndex(IHTMLElementCollection links)
        {
            try
            {
                List<NovelIndex> NovelIndexList = new List<NovelIndex>();//当前页的待插入ID列表

                foreach (HTMLAnchorElementClass el in links)//遍历所有link
                {
                    if (isNovel(el))//如果这个link是小说ID，则存到List中
                    {
                        NovelIndex temp = new NovelIndex();
                        temp.novelindex1 = Convert.ToInt32(el.href.Replace(Linkprefix,string.Empty));
                        temp.name = el.innerText;
                        NovelIndexList.Add(temp);
                    }
                }

                SaveIndex(NovelIndexList);
            }
            catch(Exception e)
            {
                MessageBox.Show("遍历连接时发生错误：" + e.Message);
                Output("遍历连接时发生错误：" + e.Message);
                Application.Exit();
            }
        }

        /// <summary>
        /// 保存novel列表到数据库
        /// </summary>
        /// <param name="lst"></param>
        private void SaveIndex(List<NovelIndex> lst)
        {
            try
            {
                this.ctx.NovelIndexes.InsertAllOnSubmit(lst);
                this.ctx.SubmitChanges();
                Output("插入第  " + this.pageindex.ToString() + "  页OK");
            }
            catch (Exception e)
            {
                
                MessageBox.Show("插入数据时发生错误，信息如下：" + e.Message);
                Output("插入数据时发生错误，信息如下：" + e.Message);
                Application.Exit();
            }
        }

        /// <summary>
        /// 判断是否是小说链接
        /// </summary>
        /// <param name="el"></param>
        /// <returns></returns>
        private bool isNovel(HTMLAnchorElementClass el)
        {
            if (!el.href.StartsWith(Linkprefix))
            {
                return false;
            }
            else if (el.href.EndsWith("=17094") || el.href.EndsWith("=42725"))
            {
                return false;
            }
            else
            {
                return true;
            }
        }




        #region 调试辅助逻辑
        private string GetDateTime()
        {
            return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        }

        private void Output(string msg)
        {
            lock (obj)
            {
                Log.WriteToFile( @"log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
            }
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                //DOM成功
                IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;

                GetIndex(vDocument.links);

                //test
                if (this.pageindex > 1895)
                {
                    Application.Exit();
                }
                //

                this.pageindex += 1;
                this.url = new Uri(URLprefix + this.pageindex.ToString() + URLsuffix);
                this.webBrowser1.Url = url;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
